import os
from PIL import Image


def compress_and_save_image(file, file_path, quality=75):
    img = Image.open(file)

    # 保存压缩后的图像
    img.save(file_path, optimize=True, quality=quality)

    return file_path


# 指定data文件夹路径
data_folder = 'static/data'

# 遍历data文件夹及其所有子文件夹
for root, dirs, files in os.walk(data_folder):
    for file in files:
        if file.endswith('.jpg') or file.endswith('.png'):
            file_path = os.path.join(root, file)

            # 压缩并覆盖保存图像
            compress_and_save_image(file_path, file_path, quality=75)

print("图片压缩完成！")
